let map;
let userId;
let otherUserId;
let curIpObj;
let meLocation = [];
let otherLocation = [];
let linMarker;
let yaoMarker;
let wqMarker;
function floatAdd(a, b) {
  let a1 = a.toString().split('.')[1].length
  let b1 = b.toString().split('.')[1].length
  let max = Math.pow(10, Math.max(a1, b1))
  return (a * max + b * max) / max
}
const methods = {
  remConfig() {
    function setRem() {
      const root = document.documentElement;
      const scale = root.clientWidth / 10;
      root.style.fontSize = scale + 'px';
      }
      setRem();
      window.addEventListener('resize', setRem);
  },
  async initMap() {
    const urlParams = new URLSearchParams(window.location.search);
    // 获取 id 参数的值
    userId = Number(urlParams.get('id'));
    otherUserId = userId === 1 ? 2 : 1;
    map = new WMap.Map('map', {
      // center: new WMap.LngLat(104.0657, 30.657428), //地图中心- 北京
      zoom: 5, //地图缩放层级
      minZoom: 0, // 最小可缩放层级
      maxZoom: 18, // 最大可缩放层级
      doubleClickZoom: true, // 是否双击放大
      zoomShow: false, // 是否显示缩放控件
      rotateShow: false, // 是否显示旋转复位控件
      fullScreen: false, // 是否显示全屏控件
      maxExtent: false, // 是否限制地图可拖动范围 - 关联 mouseMoveExtent
      mouseMoveExtent: [
        [97.21,34.19],
        [108.12,26.03]
      ]
    })
    map.on('complete', function () {
      // 地图图块加载完成后触发
      console.log('map：complete-----')
    })
    map.on('click', e => {
      console.log(e.lngLat)
    })
    // 用于获取现在的ip地址
    methods.getLocation();
    methods.getLonlatByIp();
  },
  async getLocation() {
    const res = await fetch(`https://www.linyannova.top/api/map/getLocations`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + JSON.parse(sessionStorage.getItem('user')).token
      }
    }).then(response => {
      if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
  })
    if (res.code === 0) {
      curIpObj = res;
      otherLocation = [res.data[0].longitude, res.data[0].latitude];
      res.data.map(item => {
        methods.generateMarker(item)
      })
    }
  },
  async getLonlatByIp() {
    if (navigator.geolocation){
      navigator.geolocation.getCurrentPosition(function(position) {
          const latitude = position.coords.latitude;//获取纬度
          const longitude = position.coords.longitude;//获取经度
          methods.sendLocation({longitude, latitude})
      });
    } else {
      alert('当前浏览器不支持地理定位');
    }
  },
  sendLocation({lon, lat}) {
    const data = {
      lon,
      lat,
      userId
    }
    fetch('https://www.linyannova.top/api/map/sendLocation', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + JSON.parse(sessionStorage.getItem('user')).token
      },
      body: JSON.stringify(data)
    })
  },
  workDaily() {
    setInterval(() => {
      methods.getLocation()
      methods.getLonlatByIp();
    }, 10000)
  },
  generateMarker(user) {
    new WMap.Marker({
      map,
      // 上面为默认配置
      position: [user.longitude, user.latitude],
      content: `<img src="${user.avator}" alt="" style="width: 1.5rem">`,
    })
  }
}

methods.remConfig();
methods.initMap();
// methods.workDaily();

window.addEventListener('hashchange', function(event) {
  console.log('URL参数变化了:');
});
